import axios from 'axios'
import { useUserStore } from '../store/store'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: '/api',
})

// 设置请求拦截器
// 让每次请求都要携带token
request.interceptors.request.use(
  function (config) {
    const token = useUserStore().getToken
    if (token !== null) {
      config.headers['Authorization'] = token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 设置响应拦截器
request.interceptors.response.use(
  function (response) {
    if (response.data.code === 200) {
      return response.data
    }else{
      ElMessage.error(response.data.message)
      return Promise.reject("响应结果异常:"+response.data.message)
    }
  },
  function (error) {
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      // 清除本地token
      localStorage.removeItem('token')
      // 跳转到登录页
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

// 导出实例化后的axios对象
export default request